#!/usr/bin/env bash
set -euo pipefail

# Sync cert-manager Secret tls.* keys to Knative webhook expected keys
# and update caBundle in webhook configurations if needed.

NAMESPACE=${NAMESPACE:-tekton-pipelines}
SECRET_NAME=${SECRET_NAME:-triggers-webhook-certs}

log() { echo "[cert-sync] $*"; }
die() { echo "[cert-sync] ERROR: $*" >&2; exit 1; }

# Helpers to fetch base64-encoded secret fields (without decoding)
get_secret_b64() {
  local key=$1
  kubectl -n "$NAMESPACE" get secret "$SECRET_NAME" -o jsonpath="{.data.$key}" 2>/dev/null || true
}

# Required cert-manager keys
CRT_B64=$(get_secret_b64 tls.crt)
KEY_B64=$(get_secret_b64 tls.key)
CA_B64=$(get_secret_b64 ca.crt)

[[ -n "$CRT_B64" ]] || die "Secret $SECRET_NAME missing tls.crt"
[[ -n "$KEY_B64" ]] || die "Secret $SECRET_NAME missing tls.key"
[[ -n "$CA_B64" ]] || die "Secret $SECRET_NAME missing ca.crt"

# Desired webhook keys
SERVER_CRT=$(get_secret_b64 server-cert.pem)
SERVER_KEY=$(get_secret_b64 server-key.pem)
CA_PEM=$(get_secret_b64 ca-cert.pem)

CHANGED=0

if [[ "$SERVER_CRT" != "$CRT_B64" ]] || [[ -z "$SERVER_CRT" ]]; then
  log "Syncing server-cert.pem from tls.crt"
  kubectl -n "$NAMESPACE" patch secret "$SECRET_NAME" -p "{\"data\":{\"server-cert.pem\":\"$CRT_B64\"}}" >/dev/null
  CHANGED=1
fi

if [[ "$SERVER_KEY" != "$KEY_B64" ]] || [[ -z "$SERVER_KEY" ]]; then
  log "Syncing server-key.pem from tls.key"
  kubectl -n "$NAMESPACE" patch secret "$SECRET_NAME" -p "{\"data\":{\"server-key.pem\":\"$KEY_B64\"}}" >/dev/null
  CHANGED=1
fi

if [[ "$CA_PEM" != "$CA_B64" ]] || [[ -z "$CA_PEM" ]]; then
  log "Syncing ca-cert.pem from ca.crt"
  kubectl -n "$NAMESPACE" patch secret "$SECRET_NAME" -p "{\"data\":{\"ca-cert.pem\":\"$CA_B64\"}}" >/dev/null
  CHANGED=1
fi

# Update caBundle in triggers webhook configurations to match our CA
patch_ca_bundle() {
  local kind=$1 name=$2
  local count
  count=$(kubectl get "$kind" "$name" -o json | jq '.webhooks | length')
  for i in $(seq 0 $((count-1))); do
    kubectl patch "$kind" "$name" --type=json \
      -p "[{\"op\":\"replace\",\"path\":\"/webhooks/$i/clientConfig/caBundle\",\"value\":\"$CA_B64\"}]" >/dev/null
  done
}

log "Patching caBundle for Tekton Triggers webhooks"
patch_ca_bundle mutatingwebhookconfiguration webhook.triggers.tekton.dev || die "Failed to patch mutating webhook"
patch_ca_bundle validatingwebhookconfiguration validation.webhook.triggers.tekton.dev || die "Failed to patch validation webhook"
patch_ca_bundle validatingwebhookconfiguration config.webhook.triggers.tekton.dev || die "Failed to patch config webhook"

# Restart webhook if we changed secret keys
if [[ "$CHANGED" -eq 1 ]]; then
  log "Restarting tekton-triggers-webhook to reload certificates"
  kubectl -n "$NAMESPACE" rollout restart deploy tekton-triggers-webhook >/dev/null || true
fi

log "Sync completed"